<template>
  <div id="myPosition">                    <!--个股-->
    <gj-loadmore :top-method="loadTop" :bottom-method="loadBottom" ref="loadmore" :mes="mes">   <!--loadmore-->
      <div class="tips" v-if="dataList.length==0 && error!=''">{{error}}</div>                                                            <!--v-show="data.length==0"-->
      <div class="pro-item" v-for="(item, index) in dataList">       <!--模板-->                                                    <!--v-for循环的结果-->
        <div class="pro-item-lable">
          <div class="pro-item-tip bg-gray">
            <div class="pro-item-tip-type bg-df text-xs" :class="{'color-blue':item.trade_type=='0','color-red':item.trade_type=='1'}">
              {{item.trade_type=='0'? '卖出': '买入'}}
            </div>
            <div class="pro-item-tip-time m-l-sm">
              <i class="iconfont text-xs color-9">&#xe606;</i>       <!--时钟icon-->
              <span class="color-9 text-xs m-l-xs">{{item.trade_time_str}}</span>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <div class="text-center padder-v padder-sm">
          <div class="hbox" @click.stop.prevent="clickBox(item)">
            <div class="col" style="width: 25%;text-align: left;">
              <div class="text-md">{{item.stock_name}}</div>
              <div class="text-xs color-9">SH{{item.stock_code}}</div>
            </div>
            <div class="col">
              <div :class="{'buy_color':item.trade_type=='0','sell_color':item.trade_type=='1'}">{{item.trade_price}}</div>
              <div class="text-xs color-9">{{item.commission}}委托</div>
            </div>
            <div class="col" style="width: 22%;">
              <div>{{item.trade_count}}</div>
              <div class="text-xs color-9">数量</div>
            </div>
            <div class="col" style="vertical-align: bottom;" v-if="isChecked == '1'">
              <img src="../../../assets/images/yicheng.png" style="width: 57px;" class="m-t-n-sm">
            </div>
            <div class="col" style="vertical-align: bottom;" v-else>
              <img  :src ="imgUrl(item)" style='width: 57px;' class='m-t-n-sm'>
            </div>
            <div class="col text-right" v-if="item.entrust_status=='0'|| item.entrust_status=='3'" @click.stop.prevent="cancelOrder(item,index)" >
              <span class="cancel-order-btn">撤单</span>
            </div>
          </div>
        </div>
        <div class="bg-f5 pro-item-yy padder-sm text-xs color-9" v-if="item.isReason==1">
          调仓原因
          <i class="iconfont" :class="item.reason1.reasonIcon" style="font-size: inherit" v-if="item.reason1">{{item.reason1.reasonText}}</i>
          <i class="iconfont" :class="item.reason2.reasonIcon" style="font-size: inherit" v-if="item.reason2">{{item.reason2.reasonText}}</i>
          <i class="iconfont" :class="item.reason3.reasonIcon" style="font-size: inherit" v-if="item.reason3">{{item.reason3.reasonText}}</i>
        </div>
        <div class="bg-f5 pro-item-yy padder-sm text-xs color-9" v-else>
          暂无调仓原因
        </div>
      </div>
    </gj-loadmore>
  </div>
</template>
<script>
  import LoadMore from 'components/LoadMore'
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'
  import CommonUtil from 'common/common.util'
  export default{
    components:{                                                                        /*子组件*/
      'gj-loadmore':LoadMore,
    },
    data(){
      return{
        userCode:'',
        isChecked:'0',
        dataList:[],
        start:0,
        limit:10,
        baseUrl:'',
        mes:'',
        error: ''
      }
    },
    props:{
      checkStatus:{
        type:String
      }
    },
    created(){
      this.userCode = LocalDAO.getUserCode();  //取得用户ID
    },
    mounted:function(){
      this.isChecked = this.checkStatus;
      this.$root.eventHub.$off('check')
      this.$root.eventHub.$on('check',(checkStatus)=>{   //   isChecked改变重新请求渲染数据
        this.isChecked = checkStatus;   //  更新isChecked
        this.start = 0;
        this.dataList = [];
        this.$refs.loadmore.reset();
      })
    },
    methods:{
      getPositionData(entrust_type, isChecked){
        this.error='';
        var param = {
          "func_id": this.isChecked>0?(this.isChecked==1?'11117':'11118'):'11119',    //  isChecked状态  0未选中  1 已成   2 可撤
          "client_id": this.userCode,
          "start": this.start,    //  起点
          "limit":this.limit,    //10
          "entrust_type": entrust_type
        };
        if (isChecked>0){
          RemoteDAO.callJCL11117OR11118(param,(resp)=>{
            resp = resp || {};
            if (resp.error == 0) {
              this.error = ''
              var records = resp.data.body.records || []
              this.render(records)
            } else {
              this.error = resp.data
              this.$refs.loadmore.onBottomError()
            }
          })
        }else{
          RemoteDAO.callJCL11119(param, (resp) =>{
            resp = resp || {};
            if (resp.error == 0) {
              this.error = ''
              var records = resp.data.body.records || []
              this.render(records,1)
            } else {
              this.error = resp.data
              this.$refs.loadmore.onBottomError()
            }
          });
        }
      },
      render(records, show_type){
        RemoteDAO.callGT1008((response)=> {                             //   取得系统的时间
          var date_now = "";
          if (response.error == "0") {
            date_now = response.data.body.date;
          } else {
            date_now = CommonUtil.getTodayFormatDate();    //  get date_now   得到了系统的时间
          }
          this.formatData(records, show_type, date_now)     //   there
        })
      },
      formatData(list, show_type, date_now){                         //   进入块级作用域
        let formatList = [];
        for (var i = 0; i < list.length; i++) {
          var obj = list[i];
          var tempObj = {},tradePrice = "", trade_count = "";;
          tempObj.trade_no = obj.entrust_no;//委托标示
          tempObj.market_cd = obj.exchange_type;//市场标示
          tempObj.stock_code = obj.stock_code;//股票代码
          tempObj.stock_name = obj.stock_name;//股票名称
          var isCj = "";//1、显示委托价格 2、显示成交价格
          if (this.isChecked == '2') {           //   可撤单
            tradePrice = obj.entrust_price;
            trade_count = obj.entrust_vol;
            isCj = "1";
          } else {
            if (show_type == "1") {
              if (obj.entrust_status == "2" || obj.entrust_status == "3") {
                tradePrice = obj.business_price;
                trade_count = obj.business_vol;
                isCj = "2";
              } else {
                tradePrice = obj.entrust_price;
                trade_count = obj.entrust_vol;
                isCj = "1";
              }
            } else {
              tradePrice = obj.business_price;
              trade_count = obj.business_vol;
              isCj = "2";
            }
          }
          tempObj.isCj = isCj
          tempObj.trade_price = tradePrice.toFixed(2);
          tempObj.trade_count = trade_count;
          tempObj.trade_type = CommonUtil.getBuyOrSellBuyType(obj.entrust_bs);//交易类型
          tempObj.commission = (obj.entrust_bs ==0||obj.entrust_bs ==1)?"限价": "市价";
          tempObj.entrust_status = obj.entrust_status;//委托状态
          tempObj.create_date = CommonUtil.dateFormat(obj.create_date);                               /*请问涛哥这个地方如何处理*/
          tempObj.reason1 = CommonUtil.getReasonOption(obj.reason1);        //  返回的是一个对象啊
          tempObj.reason2 = CommonUtil.getReasonOption(obj.reason2);
          tempObj.reason3 = CommonUtil.getReasonOption(obj.reason3);
          tempObj.isReason = 1;//原因默认不为空
          if (tempObj.reason1 == null && tempObj.reason2 == null && tempObj.reason3 == null) {
            tempObj.isReason = 0;//说明原因全部为空
          }
          var date = ((this.isChecked == '2' || show_type == "1") ? obj.entrust_date : obj.business_date).toString();
          var time = ((this.isChecked == '2' || show_type == "1") ? obj.entrust_time : obj.business_time).toString();
          var date_str = "";
          if (date == date_now) {
            date_str = "今天 ";
          } else {
            date_str = CommonUtil.formatDatePoint(date) + " ";
          }
          time = time.length == 5 ? "0" + time : time;
          tempObj.trade_time_str = date_str + time.substring(0, 2) + ":" + time.substring(2, 4);
          formatList.push(tempObj);
        }
        this.dataList = this.dataList.concat(formatList);
        if(this.dataList.length ==0){
          this.error = '暂无数据'
          this.$refs.loadmore.onBottomError(); //无数据
        } else if (formatList.length < this.limit) {
          this.$refs.loadmore.onBottomAllLoaded(); //全部数据加载完成
        } else {
          this.$refs.loadmore.onBottomLoaded(); //单次加载成功
          this.start += this.limit
        }
      },
      imgUrl(item){
        var url = ''
        if(item.entrust_status == '0'){
          url = require('../../../assets/images/order-status0.png')
        }else if(item.entrust_status == '1'){
          url = require('../../../assets/images/order-status1.png')
        }else if(item.entrust_status == '2'){
          url = require('../../../assets/images/order-status2.png')
        }else if(item.entrust_status == '3'){
          url = require('../../../assets/images/order-status3.png')
        }else if(item.entrust_status == '4'){
          url = require('../../../assets/images/order-status4.png')
        }else if(item.entrust_status == '5'){
          url = require('../../../assets/images/order-status5.png')
        }
        return url;
      },
      loadTop(id) {                                                                 /*下拉刷新*/
        setTimeout(()=>{
          this.start = 0;
          this.dataList = [];
          this.$refs.loadmore.reset();
          this.$refs.loadmore.onTopLoaded(); //上拉加载成功
        }, 2000)
      },
      loadBottom() {                                                                                        /*上拉加载*/
        this.getPositionData(1,this.isChecked);
      },                                                      //  撤单
      cancelOrder (item,index) {
        var param = {
          "client_id": this.userCode,
          "exchange_type":item.market_cd,
          "stock_code": item.stock_code,
          "entrust_no": item.trade_no
        };
        RemoteDAO.callJCL11115(param, (response)=> {
          if (response.error == "0") {
            var decryptData = JSON.parse(decrypt.json2(response.data));
            var body = decryptData.body || {};
            if (body.status == 0) {
              if(this.isChecked == 2){
                this.dataList.splice(index,1)
              }else{
                item.entrust_status = '1'
              }
              this.$store.dispatch('setTip',{text:"撤单成功"});
            } else {
              this.$store.dispatch('setTip',{text:body.describe !=""?body.describe:"撤单失败"});
            }
          } else {
            this.$store.dispatch('setTip', {text: "撤单失败，"+response.data});
          }
        });
      },
      clickBox(item) {
        var stockCode = item.stock_code;
        var exchangeType = item.market_cd;

        var marketCode;
        if (exchangeType == "0") {
          marketCode = "SZ";
        } else if (exchangeType == "1") {
          marketCode = "SH";
        }

        RemoteDAO.callStockLive(marketCode + stockCode, "ordinary", "1", function () {

        });
      }
    }
  }
</script>
<style scoped>
  .buy_color {
    color: #FF3333;
  }
  .sell_color {
    color: #89CD4C;
  }

  #myPosition {
    /*-webkit-overflow-scrolling: touch;*/
    overflow-y: scroll;
    /*bottom: 10px;*/
  }
</style>
